package repository

import (
	"errors"
	model "gitee.com/kordar/goadmin/admin/models"
	"gitee.com/kordar/goadmin/admin/util"
	logger "github.com/kordar/gologger"
	"gorm.io/gorm"
	"strconv"
	"time"
)

type AdminRepository struct {
	db *gorm.DB
}

func NewAdminRepository(db *gorm.DB) *AdminRepository {
	return &AdminRepository{db: db}
}

// Register 注册管理员
func (repos AdminRepository) Register(username string, phone string, password string) bool {
	sysAdmin := model.SysAdmin{}
	sysAdmin.Username = username
	sysAdmin.Phone = phone
	sysAdmin.Salt = strconv.Itoa(util.GenerateSalt())
	sysAdmin.Avatar = util.GenerateAvatar()
	sysAdmin.Password = util.GeneratePassword(password, sysAdmin.Salt)
	sysAdmin.CreateTime = time.Now()
	sysAdmin.UpdateTime = time.Now()
	create := repos.db.Create(&sysAdmin)
	return create.RowsAffected > 0
}

// LoginByToken 通过token进行登录
func (repos AdminRepository) LoginByToken(token string) (model.SysAdmin, error) {
	adminToken := model.SysAdminToken{}
	first := repos.db.Where("token = ?", token).First(&adminToken)
	if first.Error != nil {
		return model.SysAdmin{}, first.Error
	}
	return repos.FindOne(adminToken.UserID)
}

// Login 通过用户名+密码进行登录
func (repos AdminRepository) Login(username string, password string) (model.SysAdmin, error) {
	sysAdmin := model.SysAdmin{}
	first := repos.db.Where("username = ?", username).First(&sysAdmin)
	if first.Error != nil {
		return sysAdmin, errors.New("account does not exist")
	}

	token := util.GeneratePassword(password, sysAdmin.Salt)
	if token == sysAdmin.Password {
		return sysAdmin, nil
	} else {
		return sysAdmin, errors.New("incorrect password")
	}
}

// FindOne 通过管理员id获取管理员对象
func (repos AdminRepository) FindOne(id int64) (model.SysAdmin, error) {
	sysAdmin := model.SysAdmin{}
	first := repos.db.
		Where("id = ?", id).
		First(&sysAdmin)
	return sysAdmin, first.Error
}

// ResetPassword 重置密码
func (repos AdminRepository) ResetPassword(id int64, password string) bool {
	sysAdmin := model.SysAdmin{}
	first := repos.db.
		Where("id = ?", id).
		First(&sysAdmin)
	if first.Error != nil {
		logger.Errorf("[reset-password] err=%v", first.Error)
		return false
	}

	sysAdmin.Salt = strconv.Itoa(util.GenerateSalt())
	sysAdmin.Password = util.GeneratePassword(password, sysAdmin.Salt)
	save := repos.db.Save(&sysAdmin)
	return save.RowsAffected > 0
}

//// GetTenants 通过管理员Id获取管关联租户
//func (repos AdminRepository) GetTenants(adminID int64) []tenant.SysTenant {
//	var tenants []string
//	tx := repos.db.Model(&model.SysAdminTenant{}).Where("uid = ?", adminID).Pluck("tenant", &tenants)
//	if tx.Error != nil {
//		logger.Warnf("[get-tenants] err=%v", tx.Error)
//		return nil
//	}
//	if tenants == nil || len(tenants) == 0 {
//		return nil
//	}
//	var results []tenant.SysTenant
//	now := time.Now().Format("2006-01-02 15:04:05")
//	// 查询state=1永久，2定时, 开启中的租户
//	tx2 := repos.DB.Model(&tenant.SysTenant{}).
//		Where("sign in ? and (state = 1 or (state = 2 and begin_time < ? and end_time > ?))", tenants, now, now).
//		Find(&results)
//	if tx2.Error != nil {
//		return nil
//	}
//	return results
//}
//
//func (repos AdminRepository) GetTenant(sign string) (*tenant.SysTenant, error) {
//	var sysTenant = &tenant.SysTenant{}
//	tx := repos.DB.Model(sysTenant).Where("sign = ?", sign).First(sysTenant)
//	if tx.Error != nil {
//		return nil, errors.New("tenant.notfound")
//	}
//	if sysTenant.State == 0 {
//		return nil, errors.New("tenant.closed")
//	}
//	now := time.Now()
//	if sysTenant.State == 2 {
//		if sysTenant.BeginTime.After(now) {
//			return nil, errors.New("tenant.notactive")
//		}
//
//		if sysTenant.EndTime.Before(now) {
//			return nil, errors.New("tenant.expired")
//		}
//	}
//	return sysTenant, nil
//}
